%% Author: RD
%% Created: 2006-12-17
%% Description: TODO: Add desciption to aleph_labeler
-module(aleph_process_labeler).
-include("aleph_naming_macros.hrl").
-export([init_labeler/0,get_name/1,label_application/1,label_process/1,
         unlabel_application/0,unlabel_process/1,get_application_label/0]).

init_labeler()->
    case ets:info(?PROCESS_LABEL_TAB) of
        [{_,_}|_]->ok;                    
        undefined->ets:new(?PROCESS_LABEL_TAB,[named_table,public,ordered_set,{keypos,1}])
    end.

get_application_label()->
    Self_pid=self(),
    %io:format("get_application_label@~p lookup~p~n",[Self_pid,ets:lookup(?PROCESS_LABEL_TAB,self())]),
    case ets:lookup(?PROCESS_LABEL_TAB,Self_pid) of
         [{_,Label}|_]->Label;
                []->[]
    end.

get_name(Atom)->
    case get_application_label() of
     []->Atom;
     Label->App_name=Label++[$_|Atom], 
            try
              erlang:list_to_existing_atom(App_name)
            catch
              exit:_->ok;
              error:_->ok
            after
              erlang:list_to_atom(App_name)
            end
    end.

label_application(App_label)when erlang:is_atom(App_label)->
    label_application(atom_to_list(App_label));
label_application(App_label)when is_list(App_label)->    
    ets:insert(?PROCESS_LABEL_TAB,{self(),App_label}),
    %io:format("label_application insert~p~n",[ets:lookup(?PROCESS_LABEL_TAB,self())]),
    ok.

label_process(Result={ok,Pid})->
    Self_pid=self(),
    %io:format("label_process lookup~p~n",[ets:lookup(?PROCESS_LABEL_TAB,self())]),
    case ets:lookup(?PROCESS_LABEL_TAB,Self_pid) of
         [{_,Label}|_]->%io:format("label_process insert~p:~p~n",[Pid,Label]),
                        ets:insert(?PROCESS_LABEL_TAB,{Pid,Label});
                []->io:format("The Host[~p] of Process [~p]  cant not be labeled",[Self_pid,Pid])    
    end,
    Result;
label_process(Result)->
    Result.

unlabel_application()->
    ets:delete(?PROCESS_LABEL_TAB,self()).

unlabel_process(Pid)->
    ets:delete(?PROCESS_LABEL_TAB,Pid).


    